const express = require('express');
const path = require("path");
const session = require('express-session');
const userModel = require('../db/models/userModel');

const router = express.Router();
//配置session
router.use(session({
    //设置cookie id
    name: "s_id",
    secret: '123',
    saveUninitialized: false,
    resave: false,
    cookie: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
        }
     }
    ))
//登录页面
router.get("/login", (req, res) => {
    res.sendFile(path.resolve(__dirname, "../views/login.html"));
  });
//登录
router.post('/login', (req, res) => {
    let { username, pwd } = req.body;

    userModel.find({ username, pwd }, (err, data) => {
        if (data.length) {
            req.session.username = username;
            res.json({ msg: "登录成功", code: 200 })
            // res.redirect('/list');
        } else {
            res.json({ msg: '用户名或密码错误', code: 201 });
            // res.redirect('/login');
        }
    });

})
//注册页面
router.get("/register", (req, res) => {
    res.sendFile(path.resolve(__dirname, "../views/register.html"));
  });

router.post('/register', (req, res) => {
    let { username, pwd } = req.body;

    // 判断是否已有账号
    userModel.find({ username,pwd }, (err, data) => {
        if (data.length) {
            res.json({
                msg: "用户名已被占用",
                code: 201
            })
        } else {
            userModel.create([{ username, pwd: pwd }], (err, data) => {
                if (err) throw err;
                res.json({
                    msg: "注册成功",
                    code: 200
                })
            })
        }
    });
})
//退出
router.get("/logout", (req, res) => {
    req.session.destroy(() => {
      res.sendFile(path.resolve(__dirname, "../views/logout.html"));
    })
  });
  

module.exports = router;